import { request, distinctObj } from "../utils"
import { Toast, Dialog } from "vant"
import { applyBelong } from "../network/belong"
import { EVN, productionDomain, natDomain } from "../config/global"

/*
  用户注册 关联分享
*/
const registerUser = (vm, requestData, cb) => { 
  request({
    method: "POST",
    url: "api/Register/PostRegisterUser",
    data: requestData,
  }).then(async res => {
    let result = res.data
    if (result.success) {
      afterLogin(result, cb)
    } else {
      console.log("注册/登录用户失败...")
      // 用户已注册
      if(res.data.code === 104){
        Dialog.confirm({
          message: '该账号已注册，是否直接登录?'
        }).then(() => {
          vm.$router.push('login')
        }).catch(() => {
          // on cancel
        })
      } else{
        Toast(res.data.Msg || res.data.msg)
      }
    }
  })
}

/*
  用户登录或绑定微信号
*/
const loginOrBindUser = (vm, requestData, cb) => {
  request({
    url: "api/Login/GetUser",
    params: requestData,
  }).then(async (res) => {
    let result = res.data.Data
    if (result.success) {
      afterLogin(result, cb)
    } else {
      console.log('登录失败')
      Toast('登录失败')
    }
  })
}

async function afterLogin(result, cb) {
  let wxInfo = JSON.parse(localStorage.getItem("wxInfo"))
  let browserType = localStorage.getItem("browserType")
  let shareUser = localStorage.getItem("shareUser")
  let shareUserId = localStorage.getItem("shareUserId")
  let phone = localStorage.getItem("phone")
  let phonePassword = localStorage.getItem("phonePassword")

  // 登录成功清除之前的storage，除wxInfo
  localStorage.clear()
  localStorage.setItem("wxInfo", JSON.stringify(wxInfo))
  localStorage.setItem("browserType", browserType)
  localStorage.setItem("shareUser", shareUser)
  localStorage.setItem("shareUserId", shareUserId)
  localStorage.setItem("phone", phone)
  localStorage.setItem("phonePassword", phonePassword)

  let userKey = result.UserKey
  let userInfo = await getUserDetailToStorage(userKey)

  // 判断是否是城市运营商、主理人
  let userinfo = await getIsISPorBelong(userInfo.UserId)
  shareUser = JSON.parse(shareUser)
  // 如果不是从分享链接进来，跳过自动申请主理人流程
  if (!shareUser) {
    cb && cb()
    return false
  }
  console.log(
    "注册或登录成功后用户IsISP、IsDistributor，分享者IsISP、IsDistributor",
    userinfo.IsISP,
    userinfo.IsDistributor,
    shareUser.IsISP,
    shareUser.IsDistributor
  )

  if (
    !userinfo.IsISP &&
    !userinfo.IsDistributor &&
    shareUser.IsISP &&
    shareUser.IsDistributor
  ) {
    console.log("自动注册成为主理人")
    // 自动注册成为主理人
    let shareUser = JSON.parse(localStorage.getItem("shareUser"))
    applyBelongAuto(shareUser, cb)
  } else {
    cb && cb()
  }
}

function applyBelongAuto(shareUser, cb) {
  let wxInfo = JSON.parse(localStorage.getItem("wxInfo"))
  let shopName = ''
  let mobile = ""
  if(wxInfo){
    shopName = wxInfo.nickname
    mobile = wxInfo.nickname
  } else {
    shopName = localStorage.getItem("CellPhone")
    mobile = localStorage.getItem("CellPhone")
  }
  let requestData = {
    isHasShop: 2,
    isSelfManager: 2,
    userkey: localStorage.getItem("userKey"),
    shopName,
    mobile,
    mobileCode: "csyys007titika",
    shopAddress: "浙江省杭州市",
    occupation: "运营商下线",
    isShowLogo: false,
    logoUrl: "",
    parentId: shareUser.UserId,
    isChangeParent: true,
  }
  console.log('发起自动申请主理人请求', requestData)
  applyBelong(requestData, (res) => {
    cb && cb()
  })
}

function getUserDetailToStorage(userKey){
  return new Promise(resolve => {
    getUserDetail({ userkey: userKey }, (info) => {
      localStorage.setItem("userKey", userKey)
      localStorage.setItem("userId", info.UserId)
      localStorage.setItem("CellPhone", info.CellPhone)
      if(info.OpenId){
        let wxData = {
          openid: info.OpenId,
          unionid: info.UnionId,
          nickname: info.Nick,
          headimgurl: info.Photo,
          sex: info.Sex,
        }
        localStorage.setItem("wxInfo", JSON.stringify(wxData))
      }
      resolve(info)
    })
  })
}

function getIsISPorBelong(userId) {
  return new Promise((resolve) => {
    getUserDetailById(userId, (userInfo) => {
      // 判断是否是城市运营商
      let isISP = userInfo.IsISP
      let isBelongMan = userInfo.IsDistributor
      localStorage.setItem("isISP", isISP)
      localStorage.setItem("isBelongMan", isBelongMan)
      resolve(userInfo)
    })
  })
}

/*
  常规获取手机验证码
*/
const getPhoneCode = (requestData, cb) => {
  request({
    url: "api/Register/GetRegCode",
    params: requestData,
  }).then((res) => {
    if (res.data.Success) {
      let flag = res.data.Success
      cb && cb(flag)
    } else {
      Toast("获取手机验证码失败")
    }
  })
}

/*
  申请主理人时获取手机验证码
*/
const getApplyPhoneCode = (requestData, cb) => {
  request({
    url: "api/Distribution/GetRegCode",
    params: requestData
  }).then(res => {
    if (res.data.Success) {
      let flag = res.data.Success
      cb && cb(flag)
    } else {
      Toast("获取手机验证码失败")
    }
  })
}

/*
  获取用户商品浏览记录
*/
const getHistoryVisite = (cb) => {
  request({
    url: "api/UserCenter/GetMyVisitHistory",
    params: {
      UserKey: localStorage.getItem("userKey"),
    },
  }).then((res) => {
    if (res.data.Success) {
      let list = res.data.Data.reverse()
      list = list.filter((item) => {
        return item.ProductType === 0 // 过滤课程
      })
      // console.log(list)
      let listOne = distinctObj(list, "RealId") // 商品去重
      // console.log(listOne)
      cb && cb(listOne, list)
    } else {
      console.log("获取浏览记录失败...")
    }
  })
}

/* 
  删除指定用户商品浏览记录
*/
const delHistoryItem = (requestData, cb) => {
  request({
    method: "Delete",
    url: "api/UserCenter/DelVisitHistory",
    params: requestData,
  }).then((res) => {
    if (res.data.Success) {
      cb && cb()
    } else {
      console.log("删除指定用户商品浏览记录失败...")
      Toast(res.data.Msg)
    }
  })
}

/* 
  清空用户商品浏览记录
*/
const delHistoryAll = (cb) => {
  request({
    method: "Delete",
    url: "api/UserCenter/DelAllVisitHistory",
    params: {
      UserKey: localStorage.getItem("userKey"),
    },
  }).then((res) => {
    if (res.data.Success) {
      cb && cb()
    } else {
      console.log("删除指定用户商品浏览记录失败...")
      Toast(res.data.Msg)
    }
  })
}

/*
  获取用户基本资料
*/
const getUserInfo = (requestData, cb) => {
  request({
    url: "api/MemberCapital/Get",
    params: requestData
  }).then(res => {
    if (res.data.success) {
      let info = res.data
      cb && cb(info)
    } else {
      console.log("获取用户信息失败...")
    }
  })
}

/*
  获取用户详细资料
*/
const getUserDetail = (requestData, cb) => {
  request({
    url: "api/UserCenter/GetUser",
    params: requestData
  }).then(res => {
    if (res.data.Success) {
      let info = res.data.Data
      localStorage.setItem("userNick", info.Nick)
      localStorage.setItem("userPhoto", info.Photo)
      localStorage.setItem("ParentMember", JSON.stringify(info.ParentMember))
      cb && cb(info)
    } else {
      console.log("获取用户详细信息失败...")
    }
  })
}

/*
  根据用户UserId获取用户资料
*/
const getUserDetailById = (userId, cb) => {
  request({
    url: "api/UserCenter/GetUserById",
    params: {
      id: userId,
    },
  }).then((res) => {
    if (res.data.Success) {
      let userInfo = res.data.Data
      cb && cb(userInfo)
    } else {
      console.log("获取用户信息失败...")
    }
  })
}

/* 
  保存用户信息
*/
const saveUserInfo = (requestData, cb) => {
  request({
    method: "POST",
    url: "api/UserCenter/SaveUserInfo",
    data: requestData
  }).then(res => {
    if (res.data.Success) {
      cb && cb()
    } else {
      console.log("保存用户信息失败...")
      Toast(res.data.Msg)
    }
  })
}

/*
  获取用户积分
*/
const getUserScore = (requestData, cb) => {
  request({
    url: "api/UserCenter/GetIntegralRecord",
    params: requestData
  }).then(res => {
    if (res.data.Success) {
      let info = res.data.Data
      cb && cb(info)
    } else {
      console.log("获取用户积分失败...")
    }
  })
}

/* 
  转赠积分
*/
const sendIntegral = (requestData, cb) => {
  request({
    method: "POST",
    url: "api/MemberIntegral/SendIntegral",
    data: requestData
  }).then(res => {
    if (res.data.Success) {
      cb && cb()
    } else {
      console.log("转赠积分失败...")
      Toast(res.data.Msg)
    }
  })
}

/*
  获取用户订单列表
*/
const getUserOrders = (requestData, cb) => {
  request({
    url: "api/MemberOrder/GetOrders",
    params: requestData
  }).then(res => {
    if (res.data.Success) {
      let list = res.data.Data
      list.Orders = list.Orders.filter((item) => item.orderType !== 4)
      list.Orders = list.Orders.map((item) => {
        item.createTime = item.createTime.split('T').join(' ')
        return item
      })
      cb && cb(list)
    } else {
      console.log("获取用户订单失败...")
    }
  })
}
/*
  获取用户课程订单列表
*/
const getUserClass = (requestData, cb) => {
  request({
    url: "api/MemberOrder/GetOrders",
    params: requestData
  }).then(res => {
    if (res.data.Success) {
      let list = res.data.Data
      list.Orders = list.Orders.filter((item) => item.orderType === 4)
      list.Orders = list.Orders.map((item) => {
        item.createTime = item.createTime.split('T').join(' ')
        return item
      })
      cb && cb(list)
    } else {
      console.log("获取用户订单失败...")
    }
  })
}

/*
  获取用户订单详情
*/
const getUserOrder = (requestData, cb) => {
  request({
    url: "api/MemberOrder/GetOrderDetail",
    params: requestData
  }).then(res => {
    if (res.data.Success) {
      let order = res.data.Data
      cb && cb(order)
    } else {
      console.log("获取用户订单详情失败...")
    }
  })
}

/*
  获取用户关注的商品
*/
const getUserCollectionProduct = (requestData, cb) => {
  request({
    url: "api/UserCenter/GetUserCollectionProduct",
    params: requestData
  }).then(res => {
    if (res.data.Success) {
      let result = res.data.Data
      cb && cb(result)
    } else {
      console.log("获取用户关注的商品失败...")
    }
  })
}

/*
  获取用户关注的文章
*/
const getUserCollectionArticle = (requestData, cb) => {
  request({
    url: "api/Article/GetMyFavoriteArticle",
    params: requestData,
  }).then((res) => {
    if (res.data.Success) {
      let result = res.data.Data
      cb && cb(result)
    } else {
      console.log("获取用户关注的文章失败...")
    }
  })
}

/*
  微信js-sdk获取签名
*/
const getWechatSign = (requestData, cb) => {
  request({
    url: "api/Wx/GetWxSign",
    params: requestData,
  }).then((res) => {
    if (res.data.Success) {
      let result = res.data.Data
      cb && cb(result)
    } else {
      console.log("获取签名失败...")
    }
  })
}
/*
  获取用户联系
*/
const getUserContact = (cb) => {
  request({
    url: "api/UserCenter/GetUserContact",
    params: {
      userKey: localStorage.getItem('userKey')
    },
  }).then((res) => {
    if (res.data.Success) {
      let result = res.data.Data
      cb && cb(result)
    } else {
      console.log("获取用户联系失败...")
    }
  })
}

/*
  根据openid查询用户是否绑定手机
*/
const getBindInfo = (requestData, cb) => {
  request({
    url: "api/Login/GetMobileOrWxRegBindResult",
    params: requestData,
  }).then((res) => {
    if (res.data.Success) {
      let flag = res.data.Data
      cb && cb(flag)
    } else {
      Toast("获取绑定信息失败")
    }
  })
}

/**
 * 退出登录
 */
const logout = () => {
  localStorage.clear()
  sessionStorage.clear()

  location.href =
    EVN === "development"
      ? `${natDomain}#/entry`
      : `${productionDomain}Images/dist/#/entry` 
}

export {
  registerUser,
  loginOrBindUser,
  getHistoryVisite,
  delHistoryItem,
  delHistoryAll,
  getUserInfo,
  getUserDetail,
  saveUserInfo,
  getPhoneCode,
  getApplyPhoneCode,
  getUserScore,
  sendIntegral,
  getUserOrders,
  getUserOrder,
  getUserCollectionProduct,
  getUserCollectionArticle,
  getWechatSign,
  getUserDetailById,
  getUserContact,
  getBindInfo,
  logout,
  getUserClass,
}
